#include <sdk.h>
#ifndef CB_PRECOMP
    #include <cbeditor.h>
    #include <configmanager.h>
    #include <editormanager.h>
    #include <logmanager.h>
    #include <projectmanager.h>
    #include <cbproject.h>
#endif
#include <wx/choicdlg.h>
#include <wx/textdlg.h>
#include <wx/dir.h>
#include <wx/file.h>
#include <wx/frame.h>
#include <wx/menu.h>
#include "AICoder.h"

namespace { PluginRegistrant<AICoder> reg(_T("AICoder")); }

BEGIN_EVENT_TABLE(AICoder, cbPlugin)
    EVT_MENU(wxID_ANY, AICoder::OnAIGenerateCode)
END_EVENT_TABLE()

AICoder::AICoder() 
    : m_aiMenu(nullptr)
    , m_collaborationMenu(nullptr)
    , m_collaborationRunning(false)
    , m_isInCollaborationSession(false)
{
}

AICoder::~AICoder()
{
    StopCollaboration();
}

void AICoder::OnAttach()
{
    Manager::Get()->GetLogManager()->Log(_("AICoder 插件已加载"));

    // 创建AI菜单
    m_aiMenu = new wxMenu;
    m_aiMenu->Append(wxID_ANY, _("生成代码"), _("AI生成代码"));
    m_aiMenu->Append(wxID_ANY, _("重构当前文件"), _("AI重构代码"));
    m_aiMenu->Append(wxID_ANY, _("分析项目"), _("AI分析项目结构"));
    m_aiMenu->AppendSeparator();
    m_aiMenu->Append(wxID_ANY, _("自我重构UEStudio"), _("AI重构UEStudio自身"));

    // 创建协作菜单
    m_collaborationMenu = new wxMenu;
    m_collaborationMenu->Append(wxID_ANY, _("加入协作会话"), _("加入AI模型协作开发"));
    m_collaborationMenu->Append(wxID_ANY, _("创建模型组件"), _("创建新的AI模型组件"));
    m_collaborationMenu->Append(wxID_ANY, _("发布组件"), _("发布组件到全局库"));
    m_collaborationMenu->Append(wxID_ANY, _("组件浏览器"), _("浏览可用组件"));

    // 初始化协作框架
    InitializeCollaborationFramework();
}

void AICoder::OnRelease(bool appShutDown)
{
    StopCollaboration();
}

void AICoder::BuildMenu(wxMenuBar* menuBar)
{
    // 在"View"菜单后添加AI菜单
    int pos = menuBar->FindMenu(_("View"));
    if (pos != wxNOT_FOUND)
    {
        menuBar->Insert(pos + 1, m_aiMenu, _("&AI编程"));
        menuBar->Insert(pos + 2, m_collaborationMenu, _("&AI协作"));
    }
}

void AICoder::BuildModuleMenu(const ModuleType type, wxMenu* menu, const FileTreeData* data)
{
    if (type == mtEditorManager)
    {
        menu->AppendSeparator();
        menu->Append(wxID_ANY, _("AI生成代码"), _("使用AI生成代码"));
        menu->Append(wxID_ANY, _("AI重构代码"), _("使用AI重构当前文件"));
        menu->AppendSeparator();
        menu->Append(wxID_ANY, _("加入AI协作"), _("加入AI模型协作开发"));
    }
}

// ========== 现有功能实现 ==========

void AICoder::GenerateCode()
{
    cbEditor* editor = Manager::Get()->GetEditorManager()->GetBuiltinActiveEditor();
    if (!editor)
    {
        wxMessageBox(_("请先打开一个编辑器"), _("AICoder"));
        return;
    }

    wxString requirement = wxGetTextFromUser(
        _("请输入代码需求描述:"),
        _("AI代码生成")
    );

    if (requirement.IsEmpty())
        return;

    wxString prompt = wxString::Format(
        "作为C++专家，基于CodeBlocks 25.03代码风格，生成以下需求的代码：\n%s\n"
        "要求：使用wxWidgets框架，符合CodeBlocks编码规范",
        requirement
    );

    wxString generatedCode = CallDeepSeekAPI(prompt);

    // 使用正确的API插入代码
    editor->GetControl()->InsertText(editor->GetControl()->GetCurrentPos(), generatedCode);
}

void AICoder::RefactorCurrentFile()
{
    cbEditor* editor = Manager::Get()->GetEditorManager()->GetBuiltinActiveEditor();
    if (!editor)
    {
        wxMessageBox(_("请先打开一个编辑器"), _("AICoder"));
        return;
    }

    wxString instructions = wxGetTextFromUser(
        _("请输入重构指令:"),
        _("AI代码重构")
    );

    if (instructions.IsEmpty())
        return;

    wxString currentCode = GetCurrentFileContent();
    wxString prompt = wxString::Format(
        "重构以下C++代码，要求：%s\n\n原代码：\n```cpp\n%s\n```",
        instructions, currentCode
    );

    wxString refactoredCode = CallDeepSeekAPI(prompt);

    // 使用正确的API设置文本
    editor->GetControl()->SetText(refactoredCode);
}

wxString AICoder::CallDeepSeekAPI(const wxString& prompt)
{
    // 简化版API调用
    return wxString::Format(
        "// AI生成的代码将出现在这里\n// 需要配置有效的DeepSeek API密钥\n// 提示: %s",
        prompt
    );
}

wxString AICoder::GetCurrentFileContent()
{
    cbEditor* editor = Manager::Get()->GetEditorManager()->GetBuiltinActiveEditor();
    if (editor)
    {
        return editor->GetControl()->GetText();
    }
    return wxEmptyString;
}

// ========== 简化的协作功能实现 ==========

void AICoder::InitializeCollaborationFramework()
{
    // 初始化实时编辑器
    m_realTimeEditor = std::make_unique<CRealTimeEditor>();
    SetupCollaborationCallbacks();
    Manager::Get()->GetLogManager()->Log(_("AICoder 协作框架已初始化"));
}

void AICoder::SetupCollaborationCallbacks()
{
    m_realTimeEditor->SetChangeCallback([this](const CollaborationMessage& msg) {
        wxString status = wxString::Format("协作更新来自 %s: %s", msg.GetSender(), msg.GetContent());
        UpdateCollaborationUI(status);
        Manager::Get()->GetLogManager()->Log(status);
    });
}

void AICoder::JoinCollaborationSession()
{
    wxMessageBox(_("协作功能开发中..."), _("AI协作"));
}

void AICoder::CreateModelComponent()
{
    wxMessageBox(_("组件创建功能开发中..."), _("AI协作"));
}

void AICoder::PublishComponent()
{
    wxMessageBox(_("组件发布功能开发中..."), _("AI协作"));
}

void AICoder::ShowComponentBrowser()
{
    wxMessageBox(_("组件浏览器开发中..."), _("AI协作"));
}

// 其他简化实现...
void AICoder::OnAIGenerateCode(wxCommandEvent& event) { GenerateCode(); }
void AICoder::OnAIRefactor(wxCommandEvent& event) { RefactorCurrentFile(); }
void AICoder::OnAIAnalyze(wxCommandEvent& event) { AnalyzeProject(); }
void AICoder::OnSelfRefactor(wxCommandEvent& event) { SelfRefactorUEStudio(); }
void AICoder::OnJoinCollaboration(wxCommandEvent& event) { JoinCollaborationSession(); }
void AICoder::OnCreateComponent(wxCommandEvent& event) { CreateModelComponent(); }
void AICoder::OnPublishComponent(wxCommandEvent& event) { PublishComponent(); }
void AICoder::OnShowComponentBrowser(wxCommandEvent& event) { ShowComponentBrowser(); }

void AICoder::AnalyzeProject() { wxMessageBox(_("项目分析功能开发中..."), _("AICoder")); }
void AICoder::SelfRefactorUEStudio() { wxMessageBox(_("自我重构功能开发中..."), _("AICoder")); }
void AICoder::StartCollaborationServer() {}
void AICoder::CollaborationThread() {}
void AICoder::StopCollaboration() { m_collaborationRunning = false; }
void AICoder::HandleIncomingCollaboration(const CollaborationMessage& message) {}
void AICoder::UpdateCollaborationUI(const wxString& status) {}
wxString AICoder::GetCurrentDeveloperId() { return "developer@localhost"; }
